package wens.pig.dhm.formplugin.patrolscheme;

import cn.hutool.core.collection.ListUtil;
import dm.jdbc.util.StringUtil;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.ListboxItem;
import kd.bos.entity.cache.AppCache;
import kd.bos.entity.cache.IAppCache;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.*;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.ext.form.control.Listbox;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryData;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.*;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterBindingDataEvent;
import kd.bos.form.field.events.BasedataEditListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import org.apache.commons.lang3.StringUtils;
import wens.pig.base.common.consts.dhm.PatrolregionConstant;
import wens.pig.base.common.consts.dhm.SchemePatrolMulConstant;
import wens.pig.base.common.enums.BillStatusEnum;
import wens.pig.base.common.enums.FrequencyEnum;
import wens.pig.base.utils.ObjectUtil;
import wens.pig.base.utils.QFilterUtils;
import wens.pig.base.utils.ToolUtils;
import wens.pig.dhm.util.SchemePatrolUtils;

import java.text.Collator;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 *严密闭巡查方案（多层级）
 * coyle
 * 20231020
 */
public class SchemePatrolMulFormPlugin extends AbstractFormPlugin implements BasedataEditListener, ListboxClickListener, RowClickEventListener, BeforeF7SelectListener {

    //分录中"全部"的默认iD;
    private  final static String SELECTALLID = "00000000";
    //页面缓存
    private IAppCache appCache = AppCache.get("wens_scheme_patrol_mul");

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        // 二级分类-注册监听
        Listbox box = this.getView().getControl("wens_twotype");
        box.addListboxClickListener(this);
        //一级分录行点击监听
        EntryGrid entryGrid = this.getControl(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        entryGrid.addRowClickListener(this);
        BasedataEdit wens_sampling_three = this.getControl("wens_sampling_three");
        wens_sampling_three.addBeforeF7SelectListener(this);
        wens_sampling_three.addBasedataEditListener(this);
        BasedataEdit wens_site = this.getControl("wens_site");
        wens_site.addBeforeF7SelectListener(this);
        wens_site = this.getControl(SchemePatrolMulConstant.WENS_ONECLASS);
        wens_site.addBeforeF7SelectListener(this);
        this.addItemClickListeners("tbmain");
    }


    private void  showAllEntryData(){
        EntryGrid monthEntry = this.getControl("wens_patrolm_month");
        int[] selectRows = monthEntry.getSelectRows();
        if(selectRows.length>0) {
            DynamicObject monthObj = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, selectRows[0]);
            DynamicObjectCollection twoEntryCol = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            List<DynamicObject> twoObjList = twoEntryCol.stream().filter(object -> StringUtils.equals(object.getString(SchemePatrolMulConstant.WENS_PARTROLM_TWOEN_WENS_PARENT_ROWID),
                    monthObj.getString("id"))).collect(Collectors.toList());
            DynamicObjectCollection threeAllCol = this.getModel().getDataEntity(true).getDynamicObjectCollection("wens_entryentity");
            for (int i = 0; i < twoObjList.size(); i++) {
                DynamicObject twoObj = twoObjList.get(i);
                DynamicObjectCollection threeEntry = twoObj.getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                for (DynamicObject threeObj : threeEntry) {
                    DynamicObject object = new DynamicObject(threeAllCol.getDynamicObjectType());
                    object.set("wens_sampling_three1", threeObj.getDynamicObject("wens_sampling_three"));
                    object.set("wens_site1", threeObj.getDynamicObject("wens_site"));
                    object.set("wens_frequency1", threeObj.getString("wens_frequency"));
                    object.set("wens_average1", threeObj.getString("wens_average"));
                    object.set("wens_superior_org1", threeObj.getDynamicObject("wens_superior_org"));
                    object.set("wens_update_remarks1", threeObj.getString("wens_update_remarks"));
                    threeAllCol.add(object);
                }
            }
            this.getModel().updateEntryCache(threeAllCol);
            this.getView().updateView("wens_entryentity");
        }
    }

    /**
     * 二级分类点击事件
     * @param listboxEvent
     */
    @Override
    public void listboxClick(ListboxEvent listboxEvent) {
        String itemId = listboxEvent.getItemId();
        //显示全部
        if(StringUtils.equals(SELECTALLID,itemId)){
            //显示分录
            showDataEntry(SELECTALLID);
            //清空分录
            this.getModel().deleteEntryData("wens_entryentity");
            //分录赋值
            showAllEntryData();

        }else{
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            //显示分录
            showDataEntry("");
            for (int i = 0; i < entryEntity.size(); i++) {
                DynamicObject twotype = entryEntity.get(i);
                String selectId = twotype.getString("wens_parent_rowid") + twotype.getString("wens_sampling_two.id") + twotype.getString("wens_sampling_two.name");
                if (selectId.equals(itemId)) {
                    setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, i);
                }
            }
        }
    }

    /**
     * 显示分录
     */
    private void  showDataEntry(String showId){
        if(StringUtils.equals(showId,SELECTALLID)){
            this.getView().setVisible(true,"wens_entryentity");
            this.getView().setVisible(false,"wens_patrolm_suben");
            this.getView().setEnable(false,new String[]{ "wens_subadd", "wens_subins", "wens_advconbaritemap" , "wens_subdel"});
        }else{
            this.getView().setVisible(false,"wens_entryentity");
            this.getView().setVisible(true,"wens_patrolm_suben");
            this.getView().setEnable(true,new String[]{ "wens_subadd", "wens_subins", "wens_advconbaritemap" , "wens_subdel"});
        }


    }

    /**
     * 单据体分录点击事件
     *
     * @param evt
     */
    @Override
    public void entryRowClick(RowClickEvent evt) {
        EntryGrid entryGrid = (EntryGrid) evt.getSource();
        String entryKey = entryGrid.getEntryKey();
        switch (entryKey) {
            case SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH:
                int[] selectRows = entryGrid.getSelectRows();
                if (null != selectRows && selectRows.length != 0) {
                    EntryData entryData = entryGrid.getEntryData();
                    DynamicObject dataEntity = entryData.getDataEntitys()[selectRows[0]];
                    String id = dataEntity.getString("id");
                    DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                    int j = 0;
                    List<DynamicObject> twoTypeList = new ArrayList<>();
                    for (int i = 0; i < entryEntity.size(); i++) {
                        if (entryEntity.get(i).getString("wens_parent_rowid").equals(id)) {
                            if (j == 0) {
                                setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, i);
                                j++;
                            }
                            twoTypeList.add(entryEntity.get(i));
                        }
                    }
                    setTwoType(twoTypeList);
                    this.getView().setVisible(true, "wens_advconap");
                } else {
                    this.getView().setVisible(false, "wens_advconap");
                }
                break;
            default:
                break;
        }
    }




    /**
     * 初始化数据;
     * 20231026
     */
    private  void  addInitData(DynamicObject oneObj){
    //是否存在上级环境巡查方案（多层级）
        if(null != oneObj){
            existParentData(RequestContext.get().getOrgId(),oneObj.getLong("id"));
            Integer parent_data_count = appCache.get("parent_data_count", Integer.class);
            if (parent_data_count == 0) {
                DynamicObjectCollection wens_sampling_month = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
                if(wens_sampling_month.size() != 0){
                    ORM.create().setPrimaryKey(wens_sampling_month.get(0));
                    //给二级赋值
                    List<DynamicObject> twoTypeList = new ArrayList<>();
                    DynamicObject[] allTwoType = SchemePatrolUtils.getAllTwoType(oneObj);
                    DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                    DynamicObjectType dynamicObjectType = entryEntity.getDynamicObjectType();
                    for (DynamicObject item : allTwoType) {
                        DynamicObject dynamicObject = new DynamicObject(dynamicObjectType);
                        //根据子页面返回的值赋值
                        dynamicObject.set("wens_sampling_two", item);
                        dynamicObject.set("wens_parent_rowid", wens_sampling_month.get(0).getString("id"));
                        entryEntity.add(dynamicObject);
                        twoTypeList.add(dynamicObject);
                    }
                    setTwoType(twoTypeList);
                }
            }
        }
    }


    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        DynamicObject obj = this.getModel().getDataEntity(true);
        if(ObjectUtil.isNull(obj.getString(SchemePatrolMulConstant.NAME))){
            String string = obj.getString(SchemePatrolMulConstant.WENS_ORG + ".name");
            obj.set(SchemePatrolMulConstant.NAME,string+"严密闭巡查方案");
        }
        setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, 0);
        //分录显示
        DynamicObjectCollection monthCol = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        if(monthCol.size()>0){
            showDataEntry("");
            this.getView().setVisible(true, "wens_advconap");
        }
        this.getView().setVisible(false, SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        //新增状态
        if ("ADDNEW".equals(this.getView().getFormShowParameter().getStatus().name())) {

        } else {
            EntryGrid wens_sampling_month = this.getControl(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
            int[] selectRows = wens_sampling_month.getSelectRows();
            DynamicObject sampling_month = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, selectRows[0]);
            String id = sampling_month.getString("id");
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            DynamicObjectCollection wens_sampling_monthNew = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
            String status = this.getModel().getValue("status").toString();
            if ("A".equals(status)) {
                DynamicObject[] allTwoType = SchemePatrolUtils.getAllTwoType((DynamicObject) this.getModel().getValue(SchemePatrolMulConstant.WENS_ONECLASS));
                List<String> twoIds = new ArrayList<>();
                for (DynamicObject dynamicObject : allTwoType) {
                    twoIds.add(dynamicObject.getString("id"));
                }
                for (int j1 = 0; j1 < entryEntity.size(); j1++) {
                    DynamicObject wens_sampling_two = entryEntity.get(j1).getDynamicObject("wens_sampling_two");
                    String twoid = wens_sampling_two.getString("id");
                    if (!twoIds.contains(twoid)) {
                        DynamicObjectCollection wens_level_subentry = entryEntity.get(j1).getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                        //删除二级分类对应子分录
                        wens_level_subentry.clear();
                        //删除二级分类
                        entryEntity.remove(j1);
                        j1--;
                    }
                }
                for (int j = 0; j < allTwoType.length; j++) {
                    String idd = allTwoType[j].getString("id");
                    int num = 0;
                    for (int j1 = 0; j1 < entryEntity.size(); j1++) {
                        DynamicObject wens_sampling_two = entryEntity.get(j1).getDynamicObject("wens_sampling_two");
                        String twoid = wens_sampling_two.getString("id");
                        if (idd.equals(twoid)) {
                            num++;
                            break;
                        }
                    }
                    if (num == 0) {
                        //添加新增的二级
                        for (int j1 = 0; j1 < wens_sampling_monthNew.size(); j1++) {
                            String id1 = wens_sampling_monthNew.get(j1).getString("id");
                            DynamicObject dynamicObject = entryEntity.addNew();
                            dynamicObject.set("wens_sampling_two", allTwoType[j]);
                            dynamicObject.set("wens_parent_rowid", id1);
                        }
                    }

                }
            }

            List<DynamicObject> twoTypeList = new ArrayList<>();
            for (int i = 0; i < entryEntity.size(); i++) {
                if (entryEntity.get(i).getString("wens_parent_rowid").equals(id)) {
                    twoTypeList.add(entryEntity.get(i));
                }
            }
            setTwoType(twoTypeList);
        }
    }

    /**
     *
     */
    private void afterAddInitData(DynamicObject oneclass){
        //是否存在上级环境巡查方案（多层级）
        if(null == oneclass){
            return;
        }
        DynamicObject wens_org = this.getModel().getDataEntity().getDynamicObject("wens_org");
        existParentData(wens_org.getLong("id"),oneclass.getLong("id"));
        Integer parent_data_count = appCache.get("parent_data_count", Integer.class);
        if (parent_data_count > 0) {
            getParentData(wens_org.getLong("id"),oneclass.getLong("id"));
            this.getView().setEnable(false, new String[]{"wens_add", "wens_delete"});
            this.getView().setVisible(false, new String[]{"wens_add", "wens_delete"});
            this.getView().setVisible(true, new String[]{"wens_advconap"});
        } else {
            this.getView().setEnable(true, new String[]{"wens_add", "wens_delete"});
            this.getView().setVisible(true, new String[]{"wens_add", "wens_delete"});
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, 0);
        //新增状态
        String name = this.getView().getFormShowParameter().getStatus().name();
        if ("ADDNEW".equals(name)) {

        } else if ("EDIT".equals(name)) {
            //是否存在上级环境巡查方案（多层级）
            DynamicObject wens_org = this.getModel().getDataEntity().getDynamicObject("wens_org");
            DynamicObject oneclass = this.getModel().getDataEntity().getDynamicObject(SchemePatrolMulConstant.WENS_ONECLASS);
            long classId = oneclass.getLong("id");
            existParentData(wens_org.getLong("id"),classId);
            Integer parent_data_count = appCache.get("parent_data_count", Integer.class);
            if (parent_data_count > 0) {
                getParentData2(wens_org.getLong("id"),classId);
                this.getView().setEnable(false, new String[]{"wens_add", "wens_delete"});
                this.getView().setVisible(false, new String[]{"wens_add", "wens_delete","wens_entryentity"});
            } else {
                this.getView().setEnable(true, new String[]{"wens_add", "wens_delete"});
                this.getView().setVisible(true, new String[]{"wens_add", "wens_delete"});
                this.getView().setVisible(false, new String[]{"wens_entryentity"});
            }
        }
        String select_boxid = appCache.get("select_boxid", String.class);
        if (StringUtils.isNotBlank(select_boxid)) {
            Listbox box = this.getView().getControl("wens_twotype");
            box.activeItem(select_boxid);
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            for (int i = 0; i < entryEntity.size(); i++) {
                DynamicObject twotype = entryEntity.get(i);
                String selectId = twotype.getString("wens_parent_rowid") + twotype.getString("wens_sampling_two.id") + twotype.getString("wens_sampling_two.name");
                if (selectId.equals(select_boxid)) {
                    setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, i);
                }
            }
        }
        //隐藏上级方案
        this.getView().setVisible(false, new String[]{"wens_superior_scheme"});

    }



    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        DynamicObject org  = this.getModel().getDataEntity(true).getDynamicObject(SchemePatrolMulConstant.WENS_ORG );
        if (StringUtils.equals(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, e.getEntryProp().getName())) {
            if(null != this.getModel().getValue(SchemePatrolMulConstant.WENS_ONECLASS)){
                //新增巡查月份分录
                RowDataEntity[] rowDataEntities = e.getRowDataEntities();
                DynamicObject dataEntity = rowDataEntities[0].getDataEntity();
                ORM.create().setPrimaryKey(dataEntity);
                //给二级赋值
                DynamicObject[] allTwoType = SchemePatrolUtils.getAllTwoType((DynamicObject)this.getModel().getValue(SchemePatrolMulConstant.WENS_ONECLASS));
                DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                int size = entryEntity.size();
                List<DynamicObject> twoTypeList = new ArrayList<>();
                DynamicObjectType dynamicObjectType = entryEntity.getDynamicObjectType();
                for (DynamicObject item : allTwoType) {
                    DynamicObject dynamicObject = new DynamicObject(dynamicObjectType);
                    dynamicObject.set("seq", size + 1);
                    dynamicObject.set("wens_sampling_two", item);
                    dynamicObject.set("wens_parent_rowid", dataEntity.getPkValue());
                    entryEntity.add(dynamicObject);
                    twoTypeList.add(dynamicObject);
                }
                this.getView().updateView(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                //设置选中的行
                setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, size);
                setTwoType(twoTypeList);
                this.getView().setVisible(true, "wens_advconap");
                //如果非第一行则复制上一行的分录数据
                int rowIndex = rowDataEntities[0].getRowIndex();//当前新增的行
                if (rowIndex != 0) {
                    //上一行
                    DynamicObject wens_sampling_month = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, rowIndex - 1);
                    String id = wens_sampling_month.getString("id");
                    //当前行
                    DynamicObject wens_sampling_monthNew = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, rowIndex);
                    String idNew = wens_sampling_monthNew.getString("id");
                    //获取全部的巡查二级
                    DynamicObjectCollection wens_twotype_entry = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                    for (DynamicObject dynamicObject : wens_twotype_entry) {
                        String wens_parent_rowid = dynamicObject.getString("wens_parent_rowid");
                        if (StringUtils.equals(wens_parent_rowid, id)) {
                            //上一行对应的分录
                            DynamicObjectCollection wens_level_subentry = dynamicObject.getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                            for (DynamicObject object : wens_twotype_entry) {
                                String wens_parent_rowid1 = object.getString("wens_parent_rowid");
                                if (StringUtils.equals(wens_parent_rowid1, idNew)) {
                                    String wens_sampling_two = dynamicObject.getString("wens_sampling_two.id");
                                    String wens_sampling_two1 = object.getString("wens_sampling_two.id");
                                    if (StringUtils.equals(wens_sampling_two, wens_sampling_two1)) {
                                        //新增月份对应的分录
                                        DynamicObjectCollection addwens_level_subentry = object.getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                                        for (int i = 0; i < wens_level_subentry.size(); i++) {
                                            DynamicObject addNew = addwens_level_subentry.addNew();
                                            addNew.set("wens_sampling_three", wens_level_subentry.get(i).getDynamicObject("wens_sampling_three"));
                                            addNew.set("wens_site", wens_level_subentry.get(i).getDynamicObject("wens_site"));
                                            addNew.set("wens_frequency", wens_level_subentry.get(i).getString("wens_frequency"));
                                            addNew.set("wens_average", wens_level_subentry.get(i).getString("wens_average"));
                                            //20231216
                                            addNew.set("wens_superior_org_h", org);
                                            String  cid = rowIndex+"!"+ ToolUtils.cnulls(wens_level_subentry.get(i).getString("wens_site.id"));
                                            addNew.set("wens_cusid",cid);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    this.getView().updateView(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                }
            }
        }else if (StringUtils.equals(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, e.getEntryProp().getName())) {
            //子分录
            RowDataEntity[] rowDataEntities = e.getRowDataEntities();
            DynamicObject dataEntity = rowDataEntities[0].getDataEntity();
            int rowIndex = rowDataEntities[0].getRowIndex();//当前新增的行
            //当前行
            DynamicObject subEn = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, rowIndex);
            //设置自定义id;
            subEn.set("wens_superior_org_h", this.getModel().getDataEntity(true).getDynamicObject("wens_org"));
        }
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        //删除巡查月份分录之前
        if (StringUtils.equals(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, e.getEntryProp().getName())) {
            int[] rowIndexs = e.getRowIndexs();
            DynamicObject wens_sampling_month = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, rowIndexs[0]);
            //缓存删除的分录id
            if(null != wens_sampling_month){
                appCache.put("delete_sampling_month_id", wens_sampling_month.getString("id"));
            }
        } else if (StringUtils.equals(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, e.getEntryProp().getName())) {
            int[] rowIndexs = e.getRowIndexs();
            DynamicObject wens_level_subentry = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, rowIndexs[0]);
            if (wens_level_subentry != null) {
                DynamicObject wens_superior_org = wens_level_subentry.getDynamicObject("wens_superior_org");
                if (wens_superior_org != null) {
                    this.getView().showTipNotification("该分录属于上级方案数据，不允许删除!");
                    e.setCancel(true);
                    return;
                }
            }
        }
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
        //删除巡查月份分录
        if (StringUtils.equals(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, e.getEntryProp().getName())) {
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            String delete_sampling_month_id = appCache.get("delete_sampling_month_id", String.class);
            List<Integer> deleteRowIndex = new ArrayList();
            for (int i = 0; i < entryEntity.size(); i++) {
                if (entryEntity.get(i).getString("wens_parent_rowid").equals(delete_sampling_month_id)) {
                    deleteRowIndex.add(i);
                }
            }
            this.getModel().deleteEntryRows(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, deleteRowIndex.stream().mapToInt(Integer::intValue).toArray());
            this.getView().updateView(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            DynamicObjectCollection wens_sampling_month = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
            //删除后巡查月份自动选中最后一行
            setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, wens_sampling_month.size() - 1);
            setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, entryEntity.size() - deleteRowIndex.size() * 2);
            //获取最后一行巡查月份
            if (wens_sampling_month.size() != 0) {
                DynamicObject dynamicObject = wens_sampling_month.get(wens_sampling_month.size() - 1);
                String id = dynamicObject.getString("id");
                List<DynamicObject> twoTypeList = new ArrayList<>();
                for (int i = 0; i < entryEntity.size(); i++) {
                    if (entryEntity.get(i).getString("wens_parent_rowid").equals(id)) {
                        twoTypeList.add(entryEntity.get(i));
                    }
                }
                setTwoType(twoTypeList);
            }
        }
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        switch (itemKey) {
            case "bar_close":
                //点击"全部,时会刷分录数据,提示数据改变;所有线刷新下;
                String status = this.getModel().getDataEntity(true).getString(SchemePatrolMulConstant.STATUS);
                if(!StringUtils.equals(status, BillStatusEnum.SAVE)){
                    this.getView().invokeOperation("refresh");
                }
            default:
                break;
        }

    }


    /**
     * 设置二级分类
     */
    public void setTwoType(List<DynamicObject> data) {
        Collections.sort(data, new Comparator<DynamicObject>() {
            @Override
            public int compare(DynamicObject o1, DynamicObject o2) {
                if (null == o1) {
                    return 1;
                }
                if (StringUtils.isBlank(o1.getString("wens_sampling_two.number"))) {
                    return 1;
                }
                if (null == o2) {
                    return -1;
                }
                if (StringUtils.isBlank(o2.getString("wens_sampling_two.number"))) {
                    return -1;
                }
                return Collator.getInstance(Locale.CHINESE).compare(o1.getString("wens_sampling_two.number"), o2.getString("wens_sampling_two.number"));
            }
        });

        Listbox box = this.getView().getControl("wens_twotype");

        List<ListboxItem> itemlist = new ArrayList<>();
        //获取环境巡查位点分类-二级分类
        for (DynamicObject item : data) {
            ListboxItem listboxItem = new ListboxItem(item.getString("wens_parent_rowid") + item.getString("wens_sampling_two.id") + item.getString("wens_sampling_two.name"),
                    item.getString("wens_sampling_two.name"));
            itemlist.add(listboxItem);
        }
        //增加"全部"节点;
        itemlist.add( new ListboxItem(SELECTALLID,"全部"));

        box.addItems(itemlist);
        if (data.size() > 0) {
            String oneId = data.get(0).getString("wens_parent_rowid") + data.get(0).getString("wens_sampling_two.id") + data.get(0).getString("wens_sampling_two.name");
            box.activeItem(oneId);
            box.listboxClick(oneId);
            appCache.put("select_boxid", oneId);
        }
    }


    private void setEntrySelect(String entryKey, int row) {
        EntryGrid wens_sampling_month = this.getControl(entryKey);
        wens_sampling_month.selectRows(new int[]{row}, row);
    }

    private void insertSchemeVal(DynamicObject data, Long orgId) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        //设置上级方案值
        model.setValue("wens_superior_scheme", data);
        //保存分录所有引用的组织
        List<String> orgIds = new ArrayList<>();
        //获取上级环境巡查方案（多层级）的巡查月份分录
        DynamicObjectCollection wens_sampling_month = data.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        //获取当前单据的巡查月份
        DynamicObjectCollection wens_sampling_monthNew = model.getDataEntity(true).getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        wens_sampling_monthNew.clear();
        DynamicObjectType sampling_monthNewType = wens_sampling_monthNew.getDynamicObjectType();
        //获取上级环境巡查方案（多层级）的巡查二级分录
        DynamicObjectCollection wens_twotype_entry = data.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        //取当前单据的的巡查二级分录
        DynamicObjectCollection wens_twotype_entryNew = model.getDataEntity(true).getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        wens_twotype_entryNew.clear();

        DynamicObject[] allTwoType = SchemePatrolUtils.getAllTwoType((DynamicObject) model.getValue(SchemePatrolMulConstant.WENS_ONECLASS));
        List<String> twoIds = new ArrayList<>();
        for (DynamicObject dynamicObject : allTwoType) {
            twoIds.add(dynamicObject.getString("id"));
        }

        for (int j = 0; j < allTwoType.length; j++) {
            String id = allTwoType[j].getString("id");
            int num = 0;
            for (int j1 = 0; j1 < wens_twotype_entry.size(); j1++) {
                DynamicObject wens_sampling_two = wens_twotype_entry.get(j1).getDynamicObject("wens_sampling_two");
                String twoid = wens_sampling_two.getString("id");
                if (id.equals(twoid)) {
                    num++;
                    break;
                }
            }
            if (num == 0) {
                //添加新增的二级
                for (int j1 = 0; j1 < wens_sampling_month.size(); j1++) {
                    String id1 = wens_sampling_month.get(j1).getString("id");
                    DynamicObject dynamicObject = wens_twotype_entry.addNew();
                    dynamicObject.set("wens_sampling_two", allTwoType[j]);
                    dynamicObject.set("wens_parent_rowid", id1);
                }
            }
        }

        DynamicObjectType twotype_entryNewType = wens_twotype_entryNew.getDynamicObjectType();
        for (int i = 0; i < wens_sampling_month.size(); i++) {
            //获取月份
            String wens_months = wens_sampling_month.get(i).getString("wens_months");
            //获取备注
            String wens_remarks = wens_sampling_month.get(i).getString("wens_remarks");
            //获取id
            String id = wens_sampling_month.get(i).getString("id");
            //把值填充到当前单据
            DynamicObject newData = new DynamicObject(sampling_monthNewType);
            newData.set("wens_months", wens_months);
            newData.set("wens_remarks", wens_remarks);
            //设置id
            ORM.create().setPrimaryKey(newData);
            wens_sampling_monthNew.add(newData);
            for (int i1 = 0; i1 < wens_twotype_entry.size(); i1++) {
                //获取父级行ID
                String wens_parent_rowid = wens_twotype_entry.get(i1).getString("wens_parent_rowid");
                if (id.equals(wens_parent_rowid)) {
                    //获取巡查二级分类
                    DynamicObject wens_sampling_two = wens_twotype_entry.get(i1).getDynamicObject("wens_sampling_two");
                    if (wens_sampling_two == null) {
                        continue;
                    }
                    if (twoIds.contains(wens_sampling_two.getString("id"))) {
                        DynamicObject newData1 = new DynamicObject(twotype_entryNewType);
                        //巡查二级分类
                        newData1.set("wens_sampling_two", wens_sampling_two);
                        //父级行ID
                        newData1.set("wens_parent_rowid", newData.getString("id"));
                        wens_twotype_entryNew.add(newData1);
                        //获取当前巡查二级分类对应的子单据
                        DynamicObjectCollection wens_level_subentryNew = newData1.getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                        DynamicObjectType level_subentryNewType = wens_level_subentryNew.getDynamicObjectType();
                        //获取对应的子分录数据
                        DynamicObjectCollection wens_level_subentry = wens_twotype_entry.get(i1).getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                        for (int i2 = 0; i2 < wens_level_subentry.size(); i2++) {
                            DynamicObject newData2 = new DynamicObject(level_subentryNewType);
                            ORM.create().setPrimaryKey(newData2);
                            //巡查三级分类
                            DynamicObject wens_sampling_three = wens_level_subentry.get(i2).getDynamicObject("wens_sampling_three");
                            newData2.set("wens_sampling_three", wens_sampling_three);
                            //巡查位点
                            DynamicObject wens_site = wens_level_subentry.get(i2).getDynamicObject("wens_site");
                            newData2.set("wens_site", wens_site);
                            //巡查周期
                            String wens_frequency = wens_level_subentry.get(i2).getString("wens_frequency");
                            newData2.set("wens_frequency", wens_frequency);
                            //巡查平均间隔次数
                            String wens_average = wens_level_subentry.get(i2).getString("wens_average");
                            newData2.set("wens_average", wens_average);
                            //引用上级组织
                            DynamicObject wens_superior_org = wens_level_subentry.get(i2).getDynamicObject("wens_superior_org");
                            if (wens_superior_org != null) {
                                newData2.set("wens_superior_org", wens_superior_org);
                                newData2.set("wens_superior_org_h", wens_superior_org);
                                orgIds.add(wens_superior_org.getString("id"));
                            } else {
                                DynamicObject org = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
                                newData2.set("wens_superior_org", org);
                                newData2.set("wens_superior_org_h", org);
                            }
                            //自定义id
                            String wens_cusid = wens_level_subentry.get(i2).getString("wens_cusid");
                            newData2.set("wens_cusid", wens_cusid);
                            //变更内容
                            //String wens_update_remarks = wens_level_subentry.get(i2).getString("wens_update_remarks");
                            wens_level_subentryNew.add(newData2);
                            //缓存子分录的原巡查周期（用于巡查周期修改限制和变更记录）
                            appCache.put("wens_level_subentry_average_" + newData2.getString("id"), wens_average);
                            appCache.put("wens_level_subentry_frequency_" + newData2.getString("id"), wens_frequency);
                            FrequencyEnum enumByValue = FrequencyEnum.getEnumByValue(wens_frequency);
                            appCache.put("wens_level_subentry_string_" + newData2.getString("id")
                                    , String.format("原巡查周期:%s,巡查间隔天数:%s,", enumByValue != null ? enumByValue.getDesc() : "", wens_average));
                        }
                    }
                }
            }
        }
        //设置引用方案值
        DynamicObjectCollection wens_all_sup_scheme = data.getDynamicObjectCollection("wens_all_sup_scheme");
        //查询多层级数据根据业务单元
        QFilter qFilter = new QFilter("wens_org", QCP.in, orgIds);
        qFilter.and("wens_oneclass", QCP.equals, data.getString("wens_oneclass.id"));
        DynamicObject[] dataIds = BusinessDataServiceHelper.load(SchemePatrolMulConstant.FORMBILLID, "id", qFilter.toArray());
        List<String> ids = new ArrayList<>();
        ids.add(data.getString("id"));
        for (DynamicObject dataId : dataIds) {
            String allid = dataId.getString("id");
            if(!StringUtils.equals(allid,model.getDataEntity(true).getString("id"))){
                ids.add(allid);
            }
        }
        model.setValue("wens_all_sup_scheme", ids.toArray());

        //缓存巡查二级分类
        appCache.put("wens_twotype_entryNew", wens_twotype_entryNew);
//        model.updateEntryCache(wens_sampling_monthNew);
        view.updateView(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        view.updateView(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        view.updateView(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);

        //获取第一行巡查月份，设置动态巡查二级
        if (wens_sampling_monthNew.size() != 0) {
            DynamicObject dynamicObject = wens_sampling_monthNew.get(0);
            String id = dynamicObject.getString("id");
            List<DynamicObject> twoTypeList = new ArrayList<>();
            for (int i = 0; i < wens_twotype_entryNew.size(); i++) {
                if (wens_twotype_entryNew.get(i).getString("wens_parent_rowid").equals(id)) {
                    if (twoTypeList.size() == 0) {
                        setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, i);
                    }
                    twoTypeList.add(wens_twotype_entryNew.get(i));
                }
            }
            setEntrySelect(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH, 0);
            setTwoType(twoTypeList);
        }
        DynamicObject org = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
        this.getView().showSuccessNotification("成功引入上级【" + (org != null ? org.getString("name") : "") + "】的数据");
    }

    private void insertSchemeVal2(DynamicObject data, Long orgId) {
        IDataModel model = this.getModel();

        //获取上级环境巡查方案（多层级）的巡查月份分录
        DynamicObjectCollection wens_sampling_month = data.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        //获取当前单据的巡查月份
        DynamicObjectCollection wens_sampling_monthNew = model.getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        //获取上级环境巡查方案（多层级）的巡查二级分录
        DynamicObjectCollection wens_twotype_entry = data.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        //取当前单据的的巡查二级分录
        DynamicObjectCollection wens_twotype_entryNew = model.getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);

        for (int i = 0; i < wens_sampling_month.size(); i++) {
            //获取id
            String id = wens_sampling_month.get(i).getString("id");
            //当前单据月份分录
            try {
                wens_sampling_monthNew.get(i).getString("id");
            } catch (Exception e) {
                continue;
            }
            String nowId = wens_sampling_monthNew.get(i).getString("id");

            for (int i1 = 0; i1 < wens_twotype_entry.size(); i1++) {
                //获取父级行ID
                String wens_parent_rowid = wens_twotype_entry.get(i1).getString("wens_parent_rowid");
                if (id.equals(wens_parent_rowid)) {
                    //获取巡查二级分类
                    DynamicObject wens_sampling_two = wens_twotype_entry.get(i1).getDynamicObject("wens_sampling_two");
                    if (wens_sampling_two == null) {
                        continue;
                    }
                    //当前子分录
                    DynamicObjectCollection wens_level_subentry_W = null;
                    for (int w = 0; w < wens_twotype_entryNew.size(); w++) {
                        //获取父级行ID
                        String wens_parent_rowid_W = wens_twotype_entryNew.get(w).getString("wens_parent_rowid");
                        if (nowId.equals(wens_parent_rowid_W)) {
                            //获取巡查二级分类
                            DynamicObject wens_sampling_two_W = wens_twotype_entryNew.get(w).getDynamicObject("wens_sampling_two");
                            if (wens_sampling_two_W == null) {
                                continue;
                            }
                            if (StringUtils.equals(wens_sampling_two.getString("id"), wens_sampling_two_W.getString("id"))) {
                                //获取当前子分录
                                wens_level_subentry_W = wens_twotype_entryNew.get(w).getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                                break;
                            }
                        }
                    }
                    if (wens_level_subentry_W != null) {
                        //获取上级子分录
                        DynamicObjectCollection wens_level_subentry_S = wens_twotype_entry.get(i1).getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                        for (int i2 = 0; i2 < wens_level_subentry_W.size(); i2++) {
                            //获取当前巡查位点
                            DynamicObject wens_site = wens_level_subentry_W.get(i2).getDynamicObject("wens_site");
                            if (wens_site == null) {
                                continue;
                            }
                            for (int i3 = 0; i3 < wens_level_subentry_S.size(); i3++) {
                                //获取上级巡查位点
                                DynamicObject wens_site_S = wens_level_subentry_S.get(i3).getDynamicObject("wens_site");
                                if (wens_site_S == null) {
                                    continue;
                                }
                                if (StringUtils.equals(wens_site.getString("id"), wens_site_S.getString("id"))) {
                                    //巡查周期
                                    String wens_frequency = wens_level_subentry_S.get(i3).getString("wens_frequency");
                                    //巡查平均间隔次数
                                    String wens_average = wens_level_subentry_S.get(i3).getString("wens_average");
                                    //缓存子分录的原巡查周期（用于巡查周期修改限制和变更记录）
                                    appCache.put("wens_level_subentry_average_" + wens_level_subentry_W.get(i2).getString("id"), wens_average);
                                    appCache.put("wens_level_subentry_frequency_" + wens_level_subentry_W.get(i2).getString("id"), wens_frequency);
                                    FrequencyEnum enumByValue = FrequencyEnum.getEnumByValue(wens_frequency);
                                    appCache.put("wens_level_subentry_string_" + wens_level_subentry_W.get(i2).getString("id")
                                            , String.format("原巡查周期:%s,巡查间隔天数:%s,", enumByValue != null ? enumByValue.getDesc() : "", wens_average));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);

    }

    /**
     * 清理分录数据
     */
    private  void  clearAllData(){
        this.getModel().deleteEntryData(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
        this.getModel().deleteEntryData(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
        this.getModel().deleteEntryData(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
        Listbox box = this.getView().getControl("wens_twotype");
        List<ListboxItem> itemlist = new ArrayList<>();
        box.addItems(itemlist);
    }
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String changeId = e.getProperty().getName();
        switch (changeId) {
            case SchemePatrolMulConstant.WENS_ONECLASS :
                clearAllData();
                DynamicObject newVal = (DynamicObject)e.getChangeSet()[0].getNewValue();
                addInitData( newVal);
                afterAddInitData(newVal);
                break;
            case SchemePatrolMulConstant.WENS_PATROLM_MONTH_WENS_MONTHS:
                clickMonth(e);
                break;
            case "wens_frequency":
                ChangeData[] changeSet = e.getChangeSet();
                int rowIndex = changeSet[0].getRowIndex();
                String newValue = changeSet[0].getNewValue().toString();
                if (StringUtils.equals(newValue, "1")) {
                    this.getModel().setValue("wens_average", "", rowIndex);
                }
                break;
            case "wens_site":
                ChangeData[] changeSet1 = e.getChangeSet();
                int rowIndex1 = changeSet1[0].getRowIndex();
                DynamicObject wens_level_subentry1 = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, rowIndex1);
//                DynamicObject wens_site = wens_level_subentry1.getDynamicObject("wens_site");
                DynamicObject wens_site = (DynamicObject)changeSet1[0].getNewValue();
                if (wens_site != null) {
                    boolean isFlag = false;
                    String siteId = ToolUtils.cnulls(wens_site.getPkValue());

                    //这块的设想是,下级先新增位点,后上级后面再新增了相同的位点,(这时所有下级又会重新根据上级生成一条数据),
                    // 为了避免下级又新增一条此位点,所以做id同步;取下级的id作为上级的id; 但如有几个下级的评级组织先加入股了这个位点,则这个位点会有两个id
                    //还是有缺陷;一定得有个可以固定的id来做为唯一性的id; 所以还是取位点本身的id;
                    //这也有个唯一的缺陷,就是位点也可以变动.....要么上级控制位点不能更改;
                    // 否则当位点变动后,下级方案会提示"此位点已被删除;而又新增一条
                    /*
                    EntryGrid monthGrid = this.getControl("wens_patrolm_month");int[] selectRows = monthGrid.getSelectRows();
                    int seleInd = 0;
                    if(selectRows.length > 0 ){
                        seleInd= selectRows[0];
                    }
                    DynamicObject object = this.getModel().getDataEntity();
                    Long orgid = object.getLong("wens_org.id");
                    String oneclass = object.getString("wens_oneclass.id");
                    List<Long> allSubIds = OrgServiceHelper.getOrgAllSubIds(orgid, OrgViewType.Admin, false);
                    QFilter qfilter = new QFilter("wens_org.id", QCP.in, allSubIds);
                    qfilter.and(SchemePatrolMulConstant.WENS_ONECLASS , QCP.equals, oneclass);
                    qfilter.and("wens_patrolm_suben.wens_site" , QCP.equals, siteId);
                    DynamicObject[] load = BusinessDataServiceHelper.load(SchemePatrolMulConstant.FORMBILLID,
                            SchemePatrolMulConstant.ALLPROPERTY , qfilter.toArray(),"createtime asc");
                    for(DynamicObject childObj : load){
                        DynamicObjectCollection childMonCol = childObj.getDynamicObjectCollection("wens_patrolm_month");
                        if(childMonCol.size()>= (seleInd+1)){
                            DynamicObject childMon = childMonCol.get(seleInd);
                            String childMoId = ToolUtils.cnulls(childMon.getPkValue());
                            DynamicObjectCollection childTwoAll = childObj.getDynamicObjectCollection("wens_partrolm_twoen");
                            List<DynamicObject> childTwoList = childTwoAll.stream().filter(object1 -> StringUtils.equals(object1.getString("wens_parent_rowid"), childMoId)).collect(Collectors.toList());
                            for(DynamicObject childTwo: childTwoList){
                                DynamicObjectCollection subEnCol = childTwo.getDynamicObjectCollection("wens_patrolm_suben");
                                List<DynamicObject> collect = subEnCol.stream().filter(object2 -> StringUtils.equals(object2.getString("wens_site.id"), siteId)).collect(Collectors.toList());
                                if(collect.size()>0){
                                    isFlag = true;
                                    DynamicObject rowObj = collect.get(0);
                                    wens_level_subentry1.set("wens_cusid",rowObj.getString("wens_cusid"));
                                }
                            }
                        }
                    }*/

                    DynamicObject group = wens_site.getDynamicObject("group");
                    if (group != null) {
                        wens_level_subentry1.set("wens_sampling_three", group);
                    }
                    //不直接使用位点id做后续的判断,保存一个自定义id
                    EntryGrid monthGrid = this.getControl("wens_patrolm_month");
                    int[] selectRows = monthGrid.getSelectRows();
                    int seleInd = 0;
                    if(selectRows.length > 0 ){
                        seleInd= selectRows[0];
                    }
                    //使用"!"隔开;
                    wens_level_subentry1.set("wens_cusid",seleInd+"!"+siteId);
                    this.getView().updateView("wens_sampling_three", rowIndex1);
                }
                break;
            case "wens_sampling_three":
                ChangeData[] changeSet2 = e.getChangeSet();
                int rowIndex2 = changeSet2[0].getRowIndex();
                this.getModel().setValue("wens_site", null, rowIndex2);
                break;
            case "wens_average":
                ChangeData[] changeSet3 = e.getChangeSet();
                int rowIndex3 = changeSet3[0].getRowIndex();
                DynamicObject wens_level_subentry3 = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, rowIndex3);
                DynamicObject wens_superior_org3 = wens_level_subentry3.getDynamicObject("wens_superior_org");
                String newValue3 = changeSet3[0].getNewValue().toString();
                String wens_frequency3 = wens_level_subentry3.getString("wens_frequency");
                String oldValue = appCache.get("wens_level_subentry_average_" + wens_level_subentry3.getString("id"), String.class);
                if (oldValue == null) {
                    oldValue = "";
                }
                if (StringUtils.equals(wens_frequency3, "1")) {
                    if (!"".equals(newValue3)) {
                        if (!isInteger(newValue3) || "0".equals(newValue3)) {
                            this.getModel().setValue("wens_average", oldValue, rowIndex3);
//                            this.getModel().setValue("wens_update_remarks", "", rowIndex3);
                            this.getView().showTipNotification("巡查间隔天数只能输入大于0的正整数!");
                            return;
                        }
                    }
                }
                if (wens_superior_org3 != null) {
                    if (StringUtils.isNotBlank(oldValue) ) {
                        if (!"".equals(newValue3)) {
                            String oldFrequency = appCache.get("wens_level_subentry_frequency_" + wens_level_subentry3.getString("id"), String.class);
                            if (Double.valueOf(newValue3) > Double.valueOf(oldValue)) {
                                this.getView().showTipNotification("巡查间隔天数不允许增大，请重新调整巡查周期!");
                                if ("1".equals(oldFrequency)) {
                                    this.getModel().setValue("wens_frequency", oldFrequency, rowIndex3);
                                    this.getModel().setValue("wens_average", oldValue, rowIndex3);
                                } else {
                                    this.getModel().setValue("wens_frequency", oldValue, rowIndex3);
                                }
                            }
                        }
                    }
                }
                break;
            default:
                break;

        }
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(str).matches();
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        checkOrg(getView().getFormShowParameter());
        FormOperate formOperate = (FormOperate) args.getSource();
        //
        if (StringUtils.equals("newentry", formOperate.getOperateKey()) ) {
            if(null == this.getModel().getValue(SchemePatrolMulConstant.WENS_ONECLASS)){
                this.getView().showTipNotification("请您先选择<一级区域分类>的数据!", 3000);
                args.setCancel(true);
            }
        }else if (StringUtils.equals(formOperate.getOperateKey(), "submit")) {
            String errorMes = "";
            DynamicObject activeRow = this.getModel().getDataEntity(true);
            //获取巡查月份
            DynamicObjectCollection wens_sampling_month = activeRow.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
            //获取二级分类分录
            DynamicObjectCollection wens_twotype_entry = activeRow.getDynamicObjectCollection(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            for (int i = 0; i < wens_twotype_entry.size(); i++) {
                String wens_parent_rowid = wens_twotype_entry.get(i).getString("wens_parent_rowid");
                DynamicObject wens_sampling_two = wens_twotype_entry.get(i).getDynamicObject("wens_sampling_two");
                DynamicObjectCollection wens_level_subentry = wens_twotype_entry.get(i).getDynamicObjectCollection(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
                String errorIndex = "";
                for (int i1 = 0; i1 < wens_sampling_month.size(); i1++) {
                    String id = wens_sampling_month.get(i1).getString("id");
                    if (StringUtil.equals(id, wens_parent_rowid)) {
                        errorIndex = "巡查月份第" + (i1 + 1) + "行的【" + (wens_sampling_two != null ? wens_sampling_two.getString("name") : "") + "】的";
                        break;
                    }
                }
                for (int i1 = 0; i1 < wens_level_subentry.size(); i1++) {
                    DynamicObject wens_sampling_three = wens_level_subentry.get(i1).getDynamicObject("wens_sampling_three");
                    DynamicObject wens_site = wens_level_subentry.get(i1).getDynamicObject("wens_site");
                    String wens_frequency = wens_level_subentry.get(i1).getString("wens_frequency");
                    String wens_average = wens_level_subentry.get(i1).getString("wens_average");
                    if (wens_sampling_three == null&&wens_site == null&&StringUtils.isBlank(wens_frequency)&&StringUtils.isBlank(wens_average)) {
                        continue;
                    }
                    //明细分类
                    if (wens_sampling_three == null) {
                        errorMes = "第" + (i1 + 1) + "行的”明细分类“不能为空";
                        break;
                    }
                    //巡查位点
                    if (wens_site == null) {
                        errorMes = "第" + (i1 + 1) + "行的”巡查位点“不能为空";
                        break;
                    }
                    //巡查周期
                    if (StringUtils.isBlank(wens_frequency)) {
                        errorMes = "第" + (i1 + 1) + "行的”巡查周期“不能为空";
                        break;
                    }
                    //巡查间隔天数
                    if (StringUtils.isBlank(wens_average)) {
                        errorMes = "第" + (i1 + 1) + "行的”巡查间隔天数“不能为空";
                        break;
                    }
                }
                if (errorMes.length() != 0) {
                    errorMes = errorIndex + errorMes;
                    break;
                }
            }
            if (errorMes.length() != 0) {
                this.getView().showTipNotification(errorMes);
                args.setCancel(true);
            }
        }
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        if (StringUtils.equals(operateKey, "unaudit") || StringUtils.equals(operateKey, "save")
                ||StringUtils.equals(operateKey, "submit")) {
            OperationResult operationResult = args.getOperationResult();
            if(operationResult.isSuccess()){
                this.getView().invokeOperation("refresh");
            }
        }
    }

    /**
     * “种猪场”、“扩繁场”、“原种场”，“区域公猪站”
     * 对应编码
     */
    private static final List<String> ORG_PATTERN = Arrays.asList("OF-28", "OF-12", "OF-40", "OF-65");

    private void checkOrg(FormShowParameter view) {
        DynamicObject orgData = BusinessDataServiceHelper.loadSingle(RequestContext.get().getOrgId(), "bos_org", "orgpattern");

        DynamicObject orgpattern = orgData.getDynamicObject("orgpattern");
        if (orgpattern != null) {
            String patternNo = orgpattern.getString("number");
            if (ORG_PATTERN.contains(patternNo)) {
                throw new KDBizException(String.format("请在温氏集团、各事业部、三级公司、四级公司维护!"));
            }
        } else {
            throw new KDBizException(String.format("当前所选“组织单元”的『形态』为空,请检查!"));
        }
    }


    /**
     * 获取上级数据，插入上级数据
     * 新增数据
     * @param orgId
     */
    private void getParentData(Long orgId,Long oneId) {
        // 查询上级
        Map<Long, Long> map = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.OrgUnit, ListUtil.toList(Long.valueOf(orgId)));
        if (!map.isEmpty()) {
            QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
            QFilter qFilter = baseDataQFilter.and(SchemePatrolMulConstant.WENS_ORG, QCP.equals, map.get(orgId));
            qFilter.and(SchemePatrolMulConstant.WENS_ONECLASS,QCP.equals, oneId);
            DynamicObject[] schemeArr = BusinessDataServiceHelper.load(SchemePatrolMulConstant.FORMBILLID, SchemePatrolMulConstant.ALLPROPERTY, qFilter.toArray());
            if (schemeArr.length > 0) {
                DynamicObject supObj = schemeArr[0];
                insertSchemeVal(supObj, map.get(orgId));
            } else {
                // 上级数据为空，继续递归获取上级
                getParentData(map.get(orgId),oneId);
            }
        }
    }


    /**
     * 获取上级数据，插入上级数据
     * 编辑数据
     * @param orgId
     */
    private void getParentData2(Long orgId,Long oneId) {
        // 查询上级
        Map<Long, Long> map = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.Admin, ListUtil.toList(Long.valueOf(orgId)));
        if (!map.isEmpty()) {
            QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
            QFilter qFilter = baseDataQFilter.and(SchemePatrolMulConstant.WENS_ORG, QCP.equals, map.get(orgId));
            qFilter.and(SchemePatrolMulConstant.WENS_ONECLASS,QCP.equals, oneId);
            DynamicObject[] schemeArr = BusinessDataServiceHelper.load(SchemePatrolMulConstant.FORMBILLID, SchemePatrolMulConstant.ALLPROPERTY, qFilter.toArray());
            if (schemeArr.length > 0) {
                DynamicObject supObj = schemeArr[0];
                insertSchemeVal2(supObj, map.get(orgId));
            } else {
                // 上级数据为空，继续递归获取上级
                getParentData2(map.get(orgId),oneId);
            }
        }
    }

    /**
     * 判断当前组织是否存在上级环境巡查方案（多层级）
     * @param orgId
     */
    private void existParentData(Long orgId,Long oneId) {
        appCache.put("parent_data_count", 0);
        // 查询上级
        Map<Long, Long> map = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.Admin, ListUtil.toList(Long.valueOf(orgId)));
        if (!map.isEmpty()) {
            QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
            QFilter qFilter = baseDataQFilter.and(SchemePatrolMulConstant.WENS_ORG, QCP.equals, map.get(orgId))
                    .and(SchemePatrolMulConstant.WENS_ONECLASS, QCP.equals, oneId );
            DynamicObject[] schemeArr = BusinessDataServiceHelper.load(SchemePatrolMulConstant.FORMBILLID, SchemePatrolMulConstant.ALLPROPERTY, qFilter.toArray());
            if (schemeArr.length > 0) {
                Integer parent_data_count = appCache.get("parent_data_count", Integer.class);
                appCache.put("parent_data_count", parent_data_count + 1);
            } else {
                // 上级数据为空，继续递归获取上级
                existParentData(map.get(orgId),oneId);
            }
        }
    }

    /**
     * 校验日期不能重复
     *
     * @param e
     */
    public void clickMonth(PropertyChangedArgs e) {
        ChangeData changeData = e.getChangeSet()[0];
        Object wens_months = changeData.getNewValue();
        int rowIndex = changeData.getRowIndex();
        if (wens_months != null) {
            String[] data = wens_months.toString().substring(1).split(",");
            DynamicObjectCollection wens_sampling_month = this.getModel().getEntryEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PATROLM_MONTH);
            for (int i = 0; i < wens_sampling_month.size(); i++) {
                if (i == rowIndex) {
                    continue;
                }
                Object wens_month = wens_sampling_month.get(i).get(SchemePatrolMulConstant.WENS_PATROLM_MONTH_WENS_MONTHS);
                if (wens_month != null) {
                    String[] entryData = wens_month.toString().substring(1).split(",");
                    for (String item : data) {
                        for (String entryDataItem : entryData) {
                            if (item.equals(entryDataItem)) {
                                this.getView().showTipNotification("注意当前月份存在重复,请重新输入!");
                                this.getModel().setValue(SchemePatrolMulConstant.WENS_PATROLM_MONTH_WENS_MONTHS, "", rowIndex);
                                return;
                            }
                        }

                    }

                }
            }
        }
    }


    @Override
    public void beforeF7Select(BeforeF7SelectEvent evt) {
        BasedataEdit source = (BasedataEdit) evt.getSource();
        ListShowParameter formShowParameter = (ListShowParameter) evt.getFormShowParameter();
        List<QFilter> filters = formShowParameter.getListFilterParameter().getQFilters();
        if ("wens_sampling_three".equals(source.getKey())) {
            //添加巡查三级分类过滤
            QFilter qFilter = QFilterUtils.getBaseDataQFilter();
            EntryGrid wens_twotype_entry = this.getControl(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
            int[] selectRows = wens_twotype_entry.getSelectRows();
            DynamicObject classTwoEntry = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, selectRows[0]);
            DynamicObject classTwo = classTwoEntry.getDynamicObject("wens_sampling_two");
            if (null != classTwo) {
                //要找子节点分类 ,非生产线 //获取3级
                List<String> subClassData = SchemePatrolUtils.getTypeClassSubData(classTwo,"3","");
                if(null != subClassData){
                    subClassData.add(ToolUtils.cnulls(classTwo.getPkValue()));
                    qFilter.and(PatrolregionConstant.ID, QCP.in, subClassData);
                }else{
                    //为空,则要2级
                    qFilter.and(PatrolregionConstant.ID, QCP.in, classTwo.getPkValue());
                }
            } else {
                this.getView().showTipNotification("巡查二级分类为空,请先选择!", 4000);
                qFilter.and(PatrolregionConstant.ID, QCP.equals, "null001");
            }
            filters.add(qFilter);
        } else if ("wens_site".equals(source.getKey())) {
            DynamicObjectCollection wens_level_subentry = this.getModel().getEntryEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN);
            List<String> existSite = new ArrayList<>();
            for (DynamicObject dynamicObject : wens_level_subentry) {
                DynamicObject wens_site = dynamicObject.getDynamicObject("wens_site");
                if (wens_site != null) {
                    existSite.add(wens_site.getString("id"));
                }
            }
            //添加巡查位点过滤
            int row = evt.getRow();
            DynamicObject level_subentry = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.SUBENTRYENTITYID_WENS_PATROLM_SUBEN, row);
            DynamicObject threeObj = level_subentry.getDynamicObject("wens_sampling_three");
            QFilter qFilters = QFilterUtils.getBaseDataQFilter();
            if (existSite.size() > 0) {
                //针对已选择的数据过滤点
                qFilters.and(new QFilter("id", QCP.not_in, existSite));
            }
            ArrayList<Long> subIdSet = new ArrayList<>();
            if (null!=threeObj) {
                SchemePatrolUtils.getSubClass(threeObj,subIdSet);
                //加入自身
                subIdSet.add((Long)threeObj.getPkValue());
                qFilters.and(new QFilter("group.id", QCP.equals, subIdSet));
            } else {
                EntryGrid wens_twotype_entry = this.getControl(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN);
                int[] selectRows = wens_twotype_entry.getSelectRows();
                DynamicObject twotype_entry = this.getModel().getEntryRowEntity(SchemePatrolMulConstant.ENTRYENTITYID_WENS_PARTROLM_TWOEN, selectRows[0]);
                //根据二级id获取的下级
                if (twotype_entry != null) {
                    DynamicObject wens_sampling_two = twotype_entry.getDynamicObject("wens_sampling_two");
                    SchemePatrolUtils.getSubClass(wens_sampling_two,subIdSet);
                    subIdSet.add((Long)wens_sampling_two.getPkValue());
                }
            }
            qFilters.and(new QFilter("group.id", QCP.in, subIdSet));
            filters.add(qFilters);
        }else if (SchemePatrolMulConstant.WENS_ONECLASS.equals(source.getKey())) {
            QFilter qFilters = QFilterUtils.getBaseDataQFilter();
            qFilters.and(new QFilter("level", QCP.equals, "1"));
            filters.add(qFilters);
        }
    }

    private List<String> getThreeTypeIds(String longnumber) {
        QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
        QFilter qfilter = baseDataQFilter.and("longnumber", QCP.like, longnumber + "%");
        qfilter.and("longnumber", QCP.not_equals2, longnumber);
        DynamicObject[] load = BusinessDataServiceHelper.load(PatrolregionConstant.FORMBILLID, PatrolregionConstant.ALLPROPERTY, qfilter.toArray());
        List<String> list = new ArrayList<>();
        for (DynamicObject dynamicObject : load) {
            list.add(dynamicObject.getString("id"));
        }
        return list;
    }

    @Override
    public void afterBindingData(AfterBindingDataEvent afterBindingDataEvent) {

    }

//    @Override
//    public void initialize() {
//        super.initialize();
//        this.getModel().addDataModelChangeListener(this);
//        BasedataEdit wens_sampling_three = this.getControl("wens_sampling_three");
//        wens_sampling_three.addBasedataEditListener(this);
//    }
//
//    @Override
//    public void afterBindingData(AfterBindingDataEvent evt) {
//        BasedataEdit edit = (BasedataEdit) evt.getSource();
//        if ("wens_sampling_three".equals(edit.getKey())) {
//            //巡查三级的显示属性
//            Object v = evt.getDataEntity();
//            Object displayProp = "";
//            if (v == null) {
//                return;
//            }
//            BasedataEntityType dt;
//            if (((DynamicObject) v).getDataEntityType() instanceof BasedataEntityType) {
//                dt = (BasedataEntityType) ((DynamicObject) v).getDataEntityType();
//            } else {
//                dt = (BasedataEntityType) ((BasedataProp) edit.getProperty()).getComplexType();
//            }
//
//            //获取数据包中的名称字段值
//            String nameKey = dt.getNameProperty();
//            IDataEntityProperty p2 = dt.findProperty(nameKey);
//            if (p2 != null) {
//                displayProp = p2.getValueFast(v);
//                if (displayProp instanceof ILocaleString) {
//                    displayProp = displayProp.toString();
//                }
//            }
//            IDataEntityProperty p4 = dt.findProperty("fullname");
//            if (p4 != null) {
//                String fullname = p4.getValueFast(v).toString();
//                String[] split = fullname.replace(".", "-").split("-");
//                if (split.length > 3) {
//                    StringBuffer sb = new StringBuffer();
//                    for (int i = 0; i < split.length; i++) {
//                        if (i < 2) {
//                            continue;
//                        }
//                        sb.append(split[i]);
//                        if (i != split.length - 1) {
//                            sb.append(".");
//                        }
//                    }
//                    if (sb.length() > 0) {
//                        displayProp = String.format("%s", sb.toString());
//                    } else {
//                        displayProp = String.format("%s", displayProp.toString());
//                    }
//                } else {
//                    displayProp = String.format("%s", displayProp.toString());
//                }
//            }
//
//            String editSearchProp = getEditSearchProp(edit.getProperty());
//            //编辑显示属性也同步修改
//            if (StringUtils.isNotBlank(editSearchProp)) {
//                editSearchProp = editSearchProp
//                        .replace("name", displayProp == null ? "" : displayProp.toString());
//            }
//
//            //设置显示属性
//            evt.setDisplayProp(displayProp.toString());
//            //设置编辑显示属性
//            evt.setEditSearchProp(editSearchProp == null ? "" : editSearchProp.toString());
//        }
//
//    }
//
//
//
//    /**
//     * 获取配置的编辑显示属性
//     *
//     * @param property
//     * @return
//     */
//    private String getEditSearchProp(IDataEntityProperty property) {
//        BasedataProp basedataProp = null;
//
//        if ((property instanceof BasedataProp)) {
//            basedataProp = (BasedataProp) property;
//        } else if (property instanceof MulBasedataProp) {
//            basedataProp = (BasedataProp) ((MulBasedataProp) property).getRefBaseProp();
//        }
//
//        return basedataProp.getEditSearchProp();
//    }



}
